import datetime
from io import BytesIO
import io
import os
import uuid
import zipfile

from flask import Blueprint, current_app, request, jsonify, g, send_file
from app.common.tool.direction import get_filenames
from app.common.custom import CustomResponse
from app.dao import testcase_dao
from flask_jwt_extended import jwt_required, get_jwt_identity
from werkzeug.utils import secure_filename

testcase_routes = Blueprint('testcase', __name__)
  
  # 查询测试样例列表
@testcase_routes.route('/list', methods=['POST'])
@jwt_required()
def list_testcase():
  resp = CustomResponse('查询成功',200)
  try:
    uid = get_jwt_identity()
    path = current_app.config['DATA_DIR']
    user_dir = os.path.join(path, str(uid))
    filenames = get_filenames(user_dir)
    list = testcase_dao.select_testcase({"id": filenames})
    resp.data = {
       "list": list,
    }
    return jsonify(resp.to_dict()), 200
  except Exception as e:
        print(e)
        resp = CustomResponse("服务器异常", 500)
        return jsonify(resp.to_dict()), 200

@testcase_routes.route('/<filename>', methods=['GET'])
@jwt_required()
def get_testcase(filename):
    try:
        uid = get_jwt_identity()
        path = current_app.config['DATA_DIR']
        file_path = os.path.join(path, str(uid), filename)

        # 检查文件是否存在，且是否为 .zip 文件
        if not os.path.exists(file_path) or not filename.endswith('.zip'):
            return jsonify({"message": "文件不存在或格式错误"}), 404

        # 以附件形式返回 ZIP 文件
        return send_file(file_path, as_attachment=True, mimetype="application/zip")

    except Exception as e:
        print(f"服务器错误: {e}")
        return jsonify({"message": "服务器错误"}), 500

@testcase_routes.route('/<filename>', methods=['DELETE'])
@jwt_required()
def delete_testcase(filename):
  resp = CustomResponse('删除成功',200)
  try:
      uid = get_jwt_identity()
      path = current_app.config['DATA_DIR']
      file_path = os.path.join(path, str(uid), filename)

      # 确保文件存在且是 ZIP 文件
      if not os.path.exists(file_path) or not filename.endswith('.zip'):
          return jsonify({"message": "文件不存在或格式错误"}), 404

      # 删除文件
      os.remove(file_path)
      testcase_dao.delete_testcase({'id': filename})
      return jsonify(resp.to_dict()), 200

  except Exception as e:
      print(f"删除失败: {e}")
      return jsonify({"message": "服务器错误"}), 500
  
@testcase_routes.route('/updateHeader', methods=['POST'])
@jwt_required()
def update_header_testcase():
    resp = CustomResponse('更新成功',200)
    try:
        params = request.get_json()
        if not params['id'] or not params['name']:
            resp = CustomResponse('参数错误', 500)
            return jsonify(resp.to_dict()), 200
        uid = get_jwt_identity()
        path = current_app.config['DATA_DIR']
        user_dir = os.path.join(path, str(uid))
        filenames = get_filenames(user_dir)
        if filenames.count(params['id']) == 0:
            resp = CustomResponse('文件不存在', 500)
            return jsonify(resp.to_dict()), 200
        testcase_dao.update_testcase(params)
        return jsonify(resp.to_dict()), 200

    except Exception as e:
        print(f"文件上传失败: {e}")
        return jsonify({"message": "服务器错误"}), 500
  
@testcase_routes.route('/updateContent', methods=['POST'])
@jwt_required()
def update_content_testcase():
    resp = CustomResponse('更新成功',200)
    try:
        uid = get_jwt_identity()
        path = os.path.join(current_app.config['DATA_DIR'], str(uid))  # 用户目录
        os.makedirs(path, exist_ok=True)  # 确保目录存在

        # 获取上传的文件
        if 'file' not in request.files:
            return jsonify({"message": "没有检测到文件"}), 400

        file = request.files['file']
        # 确保文件是 ZIP 格式
        if not file.filename.endswith('.zip'):
            return jsonify({"message": "只能上传 ZIP 文件"}), 400

        filename = secure_filename(file.filename)  # 确保文件名安全
        print(file)
        file_path = os.path.join(path, filename)
        print(file_path)

        # 覆盖已有文件
        file.save(file_path)

        return jsonify(resp.to_dict()), 200

    except Exception as e:
        print(f"文件上传失败: {e}")
        return jsonify({"message": "服务器错误"}), 500


@testcase_routes.route('/upload', methods=['POST'])
@jwt_required()
def upload_testcase():
    resp = CustomResponse('更新成功',200)
    try:
        uid = get_jwt_identity()
        path = os.path.join(current_app.config['DATA_DIR'], str(uid))  # 用户目录
        os.makedirs(path, exist_ok=True)  # 确保目录存在

        # 获取上传的文件
        if 'file' not in request.files:
            return jsonify({"message": "没有检测到文件"}), 400

        file = request.files['file']

        # 确保文件是 ZIP 格式
        if not file.filename.endswith('.zip'):
            return jsonify({"message": "只能上传 ZIP 文件"}), 400

        filename = secure_filename(file.filename)  # 确保文件名安全

        # 生成唯一 ID
        unique_id = str(uuid.uuid4())
        zip_filename = f"{unique_id}.zip"  # 以唯一 ID 命名 ZIP
        file_path = os.path.join(path, zip_filename)


        # 覆盖已有文件
        file.save(file_path)
        testcase_dao.insert_testcase({
            "id": zip_filename,
            "name": "默认名称"
        })
        return jsonify(resp.to_dict()), 200

    except Exception as e:
        print(f"文件上传失败: {e}")
        return jsonify({"message": "服务器错误"}), 500
    
@testcase_routes.route('', methods=['POST'])
@jwt_required()
def add_testcase():
    resp = CustomResponse('新增成功', 200)
    try:
        uid = get_jwt_identity()
        path = os.path.join(current_app.config['DATA_DIR'], str(uid))  # 用户目录
        os.makedirs(path, exist_ok=True)  # 确保目录存在

        # 生成唯一 ID
        unique_id = str(uuid.uuid4())
        zip_filename = f"{unique_id}.zip"  # 以唯一 ID 命名 ZIP
        file_path = os.path.join(path, zip_filename)

        # 创建 ZIP 文件并添加 record.txt 文件
        with zipfile.ZipFile(file_path, 'w') as zipf:
            # 创建 record.txt 文件内容
            record_content = ""

            # 将 record.txt 文件写入 ZIP 中
            zipf.writestr("record.txt", record_content)

        resp.data = {
            "message": "测试用例创建成功",
            "id": unique_id,
            "filename": zip_filename
        }

        # 在数据库中插入测试用例记录
        testcase_dao.insert_testcase({
            "id": zip_filename,
            "name": "默认名称"
        })

        return jsonify(resp.to_dict()), 200

    except Exception as e:
        print(f"测试用例创建失败: {e}")
        return jsonify({"message": "服务器错误"}), 500